<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {
	
	var $eData = '';
	
	function __construct()
	{
		parent::__construct();
		$this->thor->loginstate();
		$this->logName = $this->session->userdata('username');
	}

	function index()
	{
		$this->db->order_by('u_id', 'asc');
		$this->eData['userList'] = $this->db->get('users')->result();
		
		$this->eData['logName'] = $this->logName;
		$this->load->view('mang/users', $this->eData);
	}
	
	function action()
	{
		$eID = (int)$this->input->get("id");
		
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="eError">', '</div>');
		
		$this->form_validation->set_rules('user', '用户名', 'trim|required|min_length[3]|max_length[200]|xss_clean|callback_user_check');
		$this->form_validation->set_rules('pass', '用户密码', 'trim|required|min_length[5]|max_length[200]|xss_clean|callback_pass_check');	
		$this->form_validation->set_rules('repe', '重复密码', 'trim|xss_clean|matches[pass]');
		
		if ($this->form_validation->run() == TRUE)
		{
			$eData = array();
			$eData['u_name'] = $this->input->post("user");
			
			$ePass = $this->input->post("pass");
			if(($eID == 0) || ($ePass != '**********')) $eData['u_password'] = md5(md5($ePass).'ecomma');
			
			if($eID > 0)
			{
				$this->db->where('u_id', $eID);
				$this->db->update('users', $eData);
			}
			else
			{
				$this->db->insert('users', $eData); 
			}
			
			redirect('mang/users');
		}
		else
		{
			$this->eData['eUser']     = '';
			$this->eData['ePass']     = '';
			
			$this->db->where('u_id', $eID); 
			$eColumn = $this->db->get('users')->row();
			if($eColumn)
			{
				$this->eData['eUser']     = $eColumn->u_name;
				$this->eData['ePass']     = '**********';
			}

			$this->eData['eID'] = $eID;
			$this->load->view('mang/users_action', $this->eData);
		}

	}
	
	function user_check($str)
	{
		$eID = (int)$this->input->get("id");
		$this->db->where('u_id != ', $eID); 
		$this->db->where('u_name like ', $str);
		$eRow = $this->db->get('users')->row();
		if($eRow)
		{
			$this->form_validation->set_message('user_check', '<b>登陆名称</b> 已存在，请重新输入！');
			return FALSE;
		}
		else return TRUE;
	}
	
	function pass_check($str)
	{
		$eUser = $this->input->post('username');
		
		if($eUser == $str)
		{
			$this->form_validation->set_message('pass_check', '<b>登陆密码</b> 不能和 <b>登陆名称</b> 相同！');
			return FALSE;
		}
		else return TRUE;
	}
	
	function delete()
	{
		$eID = (int)$this->input->get('id');
		if($eID == 0) $eCheckID = $this->input->post('checkID');
		else $eCheckID[] = $eID;
		
		$this->db->where_in('u_id', $eCheckID);
		$this->db->delete('users');
		
		$this->load->library('user_agent');
		redirect($this->agent->referrer());
	}
}